<?php
namespace app\partner\controller;

use app\common\cache\agent\IAgentAdminCache;
use app\common\cache\user\IUserCache;
use app\common\cache\total\PoolBidCache;
use app\common\controller\PartnerBaseController;
use app\common\enum\AgentAdminStatus;
use app\common\enum\AppType;
use app\common\enum\IsDelete;
use app\common\enum\IsPhone;
use app\common\enum\IsTrack;
use app\common\ext\IBid;
use app\common\ext\IDb;
use app\common\ext\IJPush;
use app\common\ext\UserPoolBid;

class Bid extends PartnerBaseController {

    /**
     * @功能：发布订单
     * @开发者：gys
     */
    public function add_to_pool(){
        //接收参数
        $user_id = self::get_data('user_id',self::NOT_EMPTY,'客户ID不能为空');
        $province_id  = self::get_data('province_id',self::NOT_EMPTY,"省份编号不能为空！");
        $city_id  = self::get_data('city_id',self::NOT_EMPTY,"城市编号不能为空！");
        $money = self::get_data('money',self::NOT_EMPTY,"贷款金额不能为空！");
        $period = self::get_data('period',self::NOT_EMPTY,"贷款周期不能为空！");
        $purpose = self::get_data('purpose',self::NOT_EMPTY,"贷款目的不能为空！");
        $bid_end = self::get_data('bid_end',self::NOT_EMPTY,"截止日期不能为空！");

        if(mb_strlen($purpose) > 4){
            self::set_code(self::WARNING_0001);
            self::set_msg('贷款目的不能大于4个字');
            self::send();
        }

        IDb::dbStartTrans();
        //修改用户所在省市
        $user_data['province_id'] = $province_id;
        $user_data['city_id'] = $city_id;
        $result = \app\common\ext\User::updateUser($user_id,$user_data);
        if(!$result){
            IDb::dbRollback();
            self::set_code(self::WARNING_0003);
            self::set_msg(\app\common\ext\User::getError());
            self::send();
        }

        $user_pool_bid_id = \app\common\ext\User::addToBidPool($user_id,$province_id,$city_id,$money,$period,$bid_end,$purpose,self::$info['cooperate_id'],self::$uid);
        if(!$user_pool_bid_id){
            IDb::dbRollback();
            self::set_code(self::WARNING_0004);
            self::set_msg(\app\common\ext\User::getError());
            self::send();
        }

        IDb::dbCommit();

        //删除统计缓存
        PoolBidCache::deleteNum();
        PoolBidCache::deleteMoney();

        //取得需要发送的用户信息
        $company_admin_where['cy.is_delete'] = IsDelete::No;
        $company_admin_where['ca.is_delete'] = IsDelete::No;
        $company_admin_where['ca.agent_admin_status'] = AgentAdminStatus::normal;
        $company_admin_where['cy.city_id'] = $city_id;
        $company_admin_list = IDb::getInstance("agent as cy")
            ->setDbFiled("distinct agent_admin_id,phone")
            ->setDbJoin("agent_admin as ca","cy.agent_id=ca.agent_id")
            ->setDbWhere($company_admin_where)
            ->sel();

        //循环发送消息
        foreach($company_admin_list as $item){
            //发送短信
//            ISms::Send($item['phone'], ISms::DktTenderDelivery);

            //发送推送信息
            IJPush::Push(AppType::XD,"新客户投放！","【有度信贷经理】客户池有新的客户投放，如有需要请尽快登录App抢单；",$item['agent_admin_id']);
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("user_pool_bid_id",$user_pool_bid_id);
        self::send();
    }

    /**
     * @功能：订单列表
     * @开发者：gys
     */
    public function bid_list(){
        $pool_bid_status = self::get_data('pool_bid_status');
        $bottom_id = self::get_data('bottom_id');

        if(!empty($pool_bid_status)) $where['pool_bid_status'] = $pool_bid_status;
        if(!empty($bottom_id)) $where['concat(1,lpad(user_pool_bid_id,8,0))'] = array("lt",$bottom_id);

        $where['upb.cooperate_admin_id'] = self::$uid;
        $list = IBid::getList($where,false);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("bid_list",$list);
        self::send();
    }

    /**
     * @功能：订单详情
     * @开发者：gys
     */
    public function bid_info(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");

        $where['user_pool_bid_id'] = $user_pool_bid_id;
        $where['cooperate_admin_id'] = self::$uid;
        $bid_info = IDb::getInstance('user_pool_bid')
            ->setDbWhere($where)
            ->row();
        if(empty($bid_info)){
            self::set_code(self::ERR_0001);
            self::set_msg("订单不存在！");
            self::send();
        }

        $expire_hour = get_config('OpenBidDate',0);

        $bid_info['bid_start_timestamp'] = strtotime($bid_info['bid_start']);
        $bid_info['bid_end_timestamp'] = strtotime($bid_info['bid_end']);
        $bid_info['bid_expire_timestamp'] = strtotime($bid_info['bid_end']." +{$expire_hour} hour");
        $bid_info['bid_end'] = substr($bid_info['bid_end'],0,10);
        $bid_info['open_time'] = substr($bid_info['open_time'],0,10);
        $bid_info['stop_time'] = substr($bid_info['stop_time'],0,10);

        $user_info = IUserCache::getInfo($bid_info['user_id'],['real','sex','loan_phone']);
        $bid_info['real'] =$user_info['real'];
        $bid_info['loan_phone'] = $user_info['loan_phone'];

        //判断是否已接单
        if(!empty($bid_info['agent_admin_id'])){
            $agent_admin_info = IAgentAdminCache::getInfoForDisplay($bid_info['agent_admin_id']);
            $admin_info = IDb::getInstance('agent_admin_tender')
                ->setDbFiled('agent_admin_tender_id,agent_admin_id,tender_note')
                ->setDbWhere(['user_pool_bid_id'=>$user_pool_bid_id,'agent_admin_id'=>$bid_info['agent_admin_id']])
                ->row();
            $agent_admin_info['agent_admin_tender_id'] = $admin_info['agent_admin_tender_id'];
            $agent_admin_info['tender_note'] = $admin_info['tender_note'];
            $tender_list = [$agent_admin_info];
        }else{
            $agent_admin_info = '';
            $admin_list = IDb::getInstance('agent_admin_tender')
                ->setDbFiled('agent_admin_tender_id,agent_admin_id,tender_note')
                ->setDbWhere(['user_pool_bid_id'=>$user_pool_bid_id])
                ->sel();

            $tender_list = [];
            if(is_array($admin_list)){
                foreach ($admin_list as $val){
                    $admin_info = IAgentAdminCache::getInfoForDisplay($val['agent_admin_id']);
                    $admin_info['agent_admin_tender_id'] = $val['agent_admin_tender_id'];
                    $admin_info['tender_note'] = $val['tender_note'];
                    $tender_list[] = $admin_info;
                }
            }
        }

        $bid_info['bid_start'] = substr($bid_info['bid_start'],0,10);
        $bid_info['bid_end'] = substr($bid_info['bid_end'],0,10);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("bid_info",$bid_info);
        self::set_value("agent_admin_info",$agent_admin_info);
        self::set_value("agent_admin_list",$tender_list);
        self::send();
    }

    /**
     * @功能：订单跟踪
     * @开发者：gys
     */
    public function task_list(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");
        $bottom_id = self::get_data('bottom_id');

        if(!empty($bottom_id)) $where['concat(1,lpad(user_pool_bid_task_id,8,0))'] = array("lt",$bottom_id);

        $where['user_pool_bid_id'] = $user_pool_bid_id;
        $where['task_type'] = IsTrack::Yes;
        $log_list = IDb::getInstance('user_pool_bid_task up')
            ->setDbWhere($where)
            ->setDbOrder("user_pool_bid_task_id desc")
            ->setDbLimit(10)
            ->sel();

        foreach ($log_list as &$val){
            //解析资源数据
            $val['video_list'] = empty($val['video_list']) ? [] : explode('{|}',$val['video_list']);
            $val['audio_list'] = empty($val['audio_list']) ? [] : explode('{|}',$val['audio_list']);
            $val['img_list'] = empty($val['img_list']) ? [] : explode('{|}',$val['img_list']);

            //设置排序编码
            $val['code'] = '1'.str_pad($val['user_pool_bid_task_id'],8,0,STR_PAD_LEFT);
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("evaluate_list",$log_list);
        self::send();
    }

    /**
     * @功能：获取投标经理
     * @开发者：gys
     */
    public function bid_admin_list(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");

        $where['user_pool_bid_id'] = $user_pool_bid_id;
        $tender_list = IDb::getInstance('agent_admin_tender')
            ->setDbWhere($where)
            ->sel();
        if(is_array($tender_list)){
            foreach ($tender_list as &$val){
                $admin_info = IAgentAdminCache::getInfo($val['agent_admin_id'],['real','avatar','evaluate_rate','is_company','is_real','service_ote','phone']);
                if(mb_strlen($admin_info['service_ote']) > 25){
                    $admin_info['service_ote'] = mb_substr($admin_info['service_ote'],0,25).'...';
                }
                $admin_info['is_phone'] = empty($admin_info['phone']) ? IsPhone::not : IsPhone::yes;

                $val = array_merge($admin_info,$val);
            }
        }else{
            $tender_list = [];
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("tender_list",$tender_list);
        self::send();
    }

    /**
     * @功能：开标
     * @开发者：gys
     */
    public function bid_open(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");
        $agent_admin_tender_id = self::get_data('agent_admin_tender_id',self::NOT_EMPTY,"订单编号不能为空！");

        $result = UserPoolBid::open(self::$uid,$user_pool_bid_id,$agent_admin_tender_id);
        if(!$result){
            self::set_code(self::ERR_0001);
            self::set_msg(UserPoolBid::getError());
            self::send();
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

    /**
     * @功能：确认完成
     * @开发者：gys
     */
    public function bid_finish(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");

        $result = UserPoolBid::finish(self::$uid,$user_pool_bid_id);
        if(!$result){
            self::set_code(self::ERR_0001);
            self::set_msg(UserPoolBid::getError());
            self::send();
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

    /**
     * @功能：评价
     * @开发者：gys
     */
    public function bid_evaluate(){
        //接收参数
        $user_pool_bid_id  = self::get_data('user_pool_bid_id',self::NOT_EMPTY,"订单编号不能为空！");
        $rate  = self::get_data('rate',self::NOT_EMPTY,"评分不能为空！");
        $content  = self::get_data('content',self::NOT_EMPTY,"评价不能为空！");
        $is_anonymous  = self::get_data('is_anonymous',self::NOT_EMPTY,"是否匿名不能为空！");

        $result = UserPoolBid::evaluate(self::$uid,$user_pool_bid_id,$rate,$content,$is_anonymous);
        if(!$result){
            self::set_code(self::ERR_0001);
            self::set_msg(UserPoolBid::getError());
            self::send();
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }
}
